package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.CommonResult;
import com.vehiclemanagement.entity.AccidentRecord;
import com.vehiclemanagement.service.AccidentRecordService;
import com.vehiclemanagement.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车辆事故记录控制器
 */
@RestController
@RequestMapping("/accident-record")
public class AccidentRecordController {

    @Autowired
    private AccidentRecordService accidentRecordService;
    
    @Autowired
    private VehicleService vehicleService;

    /**
     * 分页查询事故记录
     */
    @GetMapping("/list")
    public CommonResult<IPage<AccidentRecord>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Long driverId,
            @RequestParam(required = false) Integer accidentType,
            @RequestParam(required = false) Integer responsibility,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        IPage<AccidentRecord> page = accidentRecordService.pageAccidents(current, size, searchTerm, vehicleId, 
                driverId, accidentType, responsibility, status, startTime, endTime);
        
        return CommonResult.success(page);
    }

    /**
     * 根据ID获取事故记录详情
     */
    @GetMapping("/{id}")
    public CommonResult<AccidentRecord> getById(@PathVariable Long id) {
        AccidentRecord accident = accidentRecordService.getAccidentById(id);
        if (accident == null) {
            return CommonResult.failed("事故记录不存在");
        }
        return CommonResult.success(accident);
    }

    /**
     * 添加事故记录
     */
    @PostMapping
    public CommonResult<Boolean> add(@RequestBody AccidentRecord accident) {
        // 参数验证
        if (accident.getVehicleId() == null) {
            return CommonResult.failed("车辆信息不能为空");
        }
        if (accident.getAccidentTime() == null) {
            return CommonResult.failed("事故时间不能为空");
        }
        if (accident.getAccidentLocation() == null || accident.getAccidentLocation().trim().isEmpty()) {
            return CommonResult.failed("事故地点不能为空");
        }
        if (accident.getAccidentType() == null) {
            return CommonResult.failed("事故类型不能为空");
        }
        
        // 检查车辆是否存在
        if (!vehicleService.exists(accident.getVehicleId())) {
            return CommonResult.failed("车辆不存在");
        }
        
        // 计算实际损失(如果提供了费用信息)
        if (accident.getRepairCost() != null || accident.getCompensationCost() != null || accident.getInsuranceClaimAmount() != null) {
            BigDecimal repairCost = accident.getRepairCost() != null ? accident.getRepairCost() : BigDecimal.ZERO;
            BigDecimal compensationCost = accident.getCompensationCost() != null ? accident.getCompensationCost() : BigDecimal.ZERO;
            BigDecimal insuranceClaimAmount = accident.getInsuranceClaimAmount() != null ? accident.getInsuranceClaimAmount() : BigDecimal.ZERO;
            
            BigDecimal actualLoss = accidentRecordService.calculateActualLoss(repairCost, compensationCost, insuranceClaimAmount);
            accident.setActualLoss(actualLoss);
        }
        
        // 添加事故记录
        boolean result = accidentRecordService.addAccident(accident);
        
        if (result) {
            return CommonResult.success(true, "添加事故记录成功");
        } else {
            return CommonResult.failed("添加事故记录失败");
        }
    }

    /**
     * 修改事故记录
     */
    @PutMapping
    public CommonResult<Boolean> update(@RequestBody AccidentRecord accident) {
        if (accident.getId() == null) {
            return CommonResult.failed("事故记录ID不能为空");
        }
        
        // 验证记录是否存在
        AccidentRecord existingAccident = accidentRecordService.getAccidentById(accident.getId());
        if (existingAccident == null) {
            return CommonResult.failed("事故记录不存在");
        }
        
        // 计算实际损失(如果提供了费用信息)
        if (accident.getRepairCost() != null || accident.getCompensationCost() != null || accident.getInsuranceClaimAmount() != null) {
            BigDecimal repairCost = accident.getRepairCost() != null ? accident.getRepairCost() : BigDecimal.ZERO;
            BigDecimal compensationCost = accident.getCompensationCost() != null ? accident.getCompensationCost() : BigDecimal.ZERO;
            BigDecimal insuranceClaimAmount = accident.getInsuranceClaimAmount() != null ? accident.getInsuranceClaimAmount() : BigDecimal.ZERO;
            
            BigDecimal actualLoss = accidentRecordService.calculateActualLoss(repairCost, compensationCost, insuranceClaimAmount);
            accident.setActualLoss(actualLoss);
        }
        
        boolean result = accidentRecordService.updateAccident(accident);
        
        if (result) {
            return CommonResult.success(true, "修改事故记录成功");
        } else {
            return CommonResult.failed("修改事故记录失败");
        }
    }

    /**
     * 删除事故记录
     */
    @DeleteMapping("/{id}")
    public CommonResult<Boolean> delete(@PathVariable Long id) {
        // 验证记录是否存在
        AccidentRecord existingAccident = accidentRecordService.getAccidentById(id);
        if (existingAccident == null) {
            return CommonResult.failed("事故记录不存在");
        }
        
        boolean result = accidentRecordService.deleteAccident(id);
        
        if (result) {
            return CommonResult.success(true, "删除事故记录成功");
        } else {
            return CommonResult.failed("删除事故记录失败");
        }
    }

    /**
     * 处理事故记录
     */
    @PutMapping("/handle/{id}")
    public CommonResult<Boolean> handleAccident(
            @PathVariable Long id,
            @RequestParam String handler,
            @RequestParam String handlingResult,
            @RequestParam(required = false) String remark) {
        
        // 验证事故记录是否存在
        AccidentRecord existingAccident = accidentRecordService.getAccidentById(id);
        if (existingAccident == null) {
            return CommonResult.failed("事故记录不存在");
        }
        
        boolean result = accidentRecordService.handleAccident(id, handler, handlingResult, remark);
        
        if (result) {
            return CommonResult.success(true, "处理事故记录成功");
        } else {
            return CommonResult.failed("处理事故记录失败");
        }
    }

    /**
     * 获取车辆累计维修费用
     */
    @GetMapping("/sum-repair-cost/{vehicleId}")
    public CommonResult<BigDecimal> sumRepairCost(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        BigDecimal totalAmount = accidentRecordService.sumRepairCostByVehicleId(vehicleId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取车辆累计赔偿费用
     */
    @GetMapping("/sum-compensation-cost/{vehicleId}")
    public CommonResult<BigDecimal> sumCompensationCost(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        BigDecimal totalAmount = accidentRecordService.sumCompensationCostByVehicleId(vehicleId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取车辆累计保险理赔金额
     */
    @GetMapping("/sum-insurance-claim/{vehicleId}")
    public CommonResult<BigDecimal> sumInsuranceClaim(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        BigDecimal totalAmount = accidentRecordService.sumInsuranceClaimByVehicleId(vehicleId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取车辆累计实际损失
     */
    @GetMapping("/sum-actual-loss/{vehicleId}")
    public CommonResult<BigDecimal> sumActualLoss(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        BigDecimal totalAmount = accidentRecordService.sumActualLossByVehicleId(vehicleId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取驾驶员累计事故次数
     */
    @GetMapping("/count-accidents/driver/{driverId}")
    public CommonResult<Integer> countAccidentsByDriver(@PathVariable Long driverId) {
        // 验证驾驶员是否存在
        // if (!driverService.exists(driverId)) {
        //     return CommonResult.failed("驾驶员不存在");
        // }
        
        Integer count = accidentRecordService.countAccidentsByDriverId(driverId);
        return CommonResult.success(count);
    }

    /**
     * 按月统计事故
     */
    @GetMapping("/statistics-by-month")
    public CommonResult<List<Map<String, Object>>> statisticsByMonth(@RequestParam(required = false) Integer year) {
        List<Map<String, Object>> statistics = accidentRecordService.statisticsByMonth(year);
        return CommonResult.success(statistics);
    }

    /**
     * 按事故类型统计
     */
    @GetMapping("/statistics-by-type")
    public CommonResult<List<Map<String, Object>>> statisticsByType() {
        List<Map<String, Object>> statistics = accidentRecordService.statisticsByType();
        return CommonResult.success(statistics);
    }

    /**
     * 获取事故类型列表
     */
    @GetMapping("/accident-types")
    public CommonResult<Map<Integer, String>> getAccidentTypes() {
        Map<Integer, String> accidentTypes = new HashMap<>();
        accidentTypes.put(1, "轻微事故");
        accidentTypes.put(2, "一般事故");
        accidentTypes.put(3, "重大事故");
        
        return CommonResult.success(accidentTypes);
    }

    /**
     * 获取责任认定列表
     */
    @GetMapping("/responsibility-types")
    public CommonResult<Map<Integer, String>> getResponsibilityTypes() {
        Map<Integer, String> responsibilityTypes = new HashMap<>();
        responsibilityTypes.put(1, "全责");
        responsibilityTypes.put(2, "主责");
        responsibilityTypes.put(3, "次责");
        responsibilityTypes.put(4, "无责");
        
        return CommonResult.success(responsibilityTypes);
    }

    /**
     * 获取处理状态列表
     */
    @GetMapping("/status-types")
    public CommonResult<Map<Integer, String>> getStatusTypes() {
        Map<Integer, String> statusTypes = new HashMap<>();
        statusTypes.put(0, "未处理");
        statusTypes.put(1, "处理中");
        statusTypes.put(2, "已处理");
        
        return CommonResult.success(statusTypes);
    }

    /**
     * 计算实际损失
     */
    @PostMapping("/calculate-actual-loss")
    public CommonResult<BigDecimal> calculateActualLoss(
            @RequestParam(required = false, defaultValue = "0") BigDecimal repairCost,
            @RequestParam(required = false, defaultValue = "0") BigDecimal compensationCost,
            @RequestParam(required = false, defaultValue = "0") BigDecimal insuranceClaimAmount) {
        
        BigDecimal actualLoss = accidentRecordService.calculateActualLoss(repairCost, compensationCost, insuranceClaimAmount);
        return CommonResult.success(actualLoss);
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public CommonResult<String> test() {
        return CommonResult.success("车辆事故记录API正常工作");
    }
} 